package com.example.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.example.entity.AliOSSProperties;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUtil {

    static final String endpoint = "oss-cn-shanghai.aliyuncs.com";
    static final String accessKeyId = "LTAI5tMp3SS7ibfNAzG9qWHL";
    static final String accessKeySecret = "C1sNkKONKBC0ftMc3vgb4iHlSldNSC";
    static final String bucketName = "microservice-air-resource";

    /**
     * 以下是一个实现上传文件到OSS的方法
     * objectName: 形如 "/directory/file.ext"
     * filePath: 本地文件路径
     */
    @SneakyThrows
    public static String upload(String objectName, String filePath) {

        // 创建文件对象
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists()) {
            // 文件不存在，直接返回空值
            return "";
        }

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        DefaultCredentialProvider credentialProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialProvider);
        String fileUrl = "";
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 设置存储类型为标准存储，并设置为外部可读
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // 设置存储类型
            metadata.setObjectAcl(CannedAccessControlList.PublicRead); // 设置为公共读

            // 将元数据添加到请求中
            putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            fileUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            System.out.println("Upload success: " + fileUrl);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return fileUrl;
    }

    /**
     * 实现下载文件的功能
     * @param url
     */
    @SneakyThrows
    public static String download(String url, String downloadPath){
        String ret = "";
        try{
            downloadFile(url, downloadPath);
            ret = downloadPath;
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return ret;
    }

    public static void downloadFile(String fileURL, String savePath) throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(fileURL);

        // 执行GET请求
        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            // 获取响应状态
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 从响应中获取输入流
                    InputStream inputStream = entity.getContent();
                    FileOutputStream outputStream = new FileOutputStream(savePath);

                    // 将数据写入本地文件
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }

                    // 关闭流
                    outputStream.close();
                    inputStream.close();

                    System.out.println("File downloaded to: " + savePath);
                }
            } else {
                System.out.println("File download failed. Status code: " + statusCode);
            }
        } finally {
            // 关闭响应和HttpClient
            response.close();
            httpClient.close();
        }
    }



    @SneakyThrows
    public static void main(String[] args) {
//        // 上传路径的完整路径
//        String objectName = "test/README.txt";
//        // 本地文件地址
//        String filePath = "C:\\Users\\Aprilies\\Desktop\\README.txt";
//
//        String upload = upload(objectName, filePath);




        // 填写Bucket名称，例如examplebucket。
        // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
//        String url = "https://microservice-air-resource.oss-cn-shanghai.aliyuncs.com/test/README.txt";
//        // 填写Object下载到本地的完整路径。
//        String pathName = "C:\\\\Users\\\\Aprilies\\\\Desktop\\\\downloadREADME.txt";
//
//        downloadFile(url, pathName);

    }
}
